﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
using System.Xml.Serialization;
using System.ComponentModel;

using ShootSearch.Util;

namespace ShootSearch.Common
{
    [TypeConverter(typeof(ExpandableConverter<Rule>))]
    [Serializable]
    public class Rule
    {
        [XmlAttribute]
        public string Name { get;set; }

        private RegexOptions options = RegexOptions.None;
        public RegexOptions Options
        {
            get { return options; }
            set
            {
                options = value;
                Pattern = pattern;
            }

        }

        protected string pattern;
        public string Pattern
        {
            get { return pattern; }
            set
            {
                Regex = Util.Tools.CreateRegex(value,options);
                if(Regex!=null)
                    pattern = value;
            }
        }

        public string OutputFormat { get; set; }
        public string GroupName { get; set; }
        public bool OutputHtml { get; set; }
        public List<Rule> Children { get; set; }

        /// <summary>
        /// Gets the regex
        /// </summary>
        [XmlIgnore]
        public Regex Regex { get;protected set; }

        public Rule() 
        {
            Children = new List<Rule>();
        }

        public Rule(string pattern)
        {
            Children = new List<Rule>();
            Pattern = pattern;
        }

        public Rule(string pattern, RegexOptions options)
        {
            Children = new List<Rule>();
            Options = options;
            Pattern = pattern;
        }

        public Match Match(string input)
        {
            if (Regex != null)
            {
                return this.Regex.Match(input);
            }
            else return null;
        }

        public bool IsMatch(string input)
        {
            if (Regex != null)
            {
                return this.Regex.IsMatch(input);
            }
            else return false;
        }

        public MatchCollection Matches(string input)
        {
            if (Regex != null)
            {
                return this.Regex.Matches(input);
            }
            else return null;
        }

        public string Replace(string input,string replacement)
        {
            if (Regex != null)
            {
                return this.Regex.Replace(input, replacement);
            }
            else return input;
        }
    }
}
